//
//  WBOAuthViewController.swift
//  sinaWeibo
//
//  Created by 吴熠 on 16/11/15.
//  Copyright © 2016年 吴熠. All rights reserved.
//

import UIKit

import SVProgressHUD

let oauthpath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.plist")

class WBOAuthViewController: UIViewController {

    
    //定义一个webview属性
    let webView = UIWebView()
    
    override func loadView() {
        //将根视图改为webview
        view = webView
        //webview指定代理实现代理方法
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        //添加关闭按钮dismiss
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imageName: nil, target: self, action: #selector(close))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "快捷", imageName: nil, target: self, action: #selector(fill))
        
        //开始请求授权页面加载
        loadOAuthPage()
    }
    
    @objc private func fill(){
        let jsString = "document.getElementById('userId').value = '877479310@qq.com', document.getElementById('passwd').value = '@WY199220WY@'"
        webView.stringByEvaluatingJavaScript(from: jsString)
    }
    
    private func loadOAuthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = URL(string: urlString)
        let req = URLRequest(url: url!)
        webView.loadRequest(req)
    }
    
    
    @objc private func close() {
        dismiss(animated: true, completion: nil)
    }
    
    //在页面关闭的时候dismiss掉指示器
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
    
}
    //抽取到分类中实现代理方法将模块中的功能独立出来便于维护

extension WBOAuthViewController:UIWebViewDelegate{
    //webview的代理方法
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }



    
    
    //该协议方法返回值为bool类型  返回true就可以正常工作 否则不会
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
         //http://www.itheima.com/?code=99da14a3af1a938d830544d0a013be32  格式
        let urlString = request.url?.absoluteString ?? ""
        //找到包含特殊的标记截取code
        let flag = "code="
        if urlString .contains(flag){
            //截取code
            let query = request.url?.query ?? ""
            let code = (query as NSString).substring(from: flag.characters.count)
            //获取code后使用code获取用户的token(访问接口的唯一标识)
            //获取token
//            loadAccessToken(code: code)
            WBUserAccountViewModel.shared.loadAccessToken(code: code, finished: { (isSuccess:Bool) in
                if !isSuccess{
                    //失败了
                    SVProgressHUD.showError(withStatus: "请求网络失败")
                }
                
                //成功
                print("请求成功")
                //请求成功后的根视图控制器
                NotificationCenter.default.post(name: NSNotification.Name(kNotification), object: "Welcome")
                
            })
            
            
            return false
        }
        
        return true
    }
    
//    //获取用户token
//    private func loadAccessToken(code : String){
//        let urlString = "https://api.weibo.com/oauth2/access_token"
//        //参数以字典的形式给
//        let parameters = ["client_id" : client_id,
//                          "client_secret" : client_secret,
//                          "grant_type" : "authorization_code",
//                          "code" : code,
//                          "redirect_uri" : redirect_uri]
//        HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: parameters) { (responsObject, error) in
//            if error != nil{
//                SVProgressHUD.showError(withStatus: "你这个菜逼,没网还玩个蛋蛋")
//                return
//            }
//            //请求成功
//            print(responsObject)
//            //使用access_token和uid来请求用户信息
//            self.loadUserInfo(dict:responsObject as! [String : Any])
//        }
//    }
//    
//    //使用access_token和uid来请求用户信息
//    private func loadUserInfo(dict:[String : Any]){
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        let token = dict["access_token"]
//        //用惊叹号的原因 文档中:参数uid与screen_name二者必选其一，且只能选其一(http://open.weibo.com/wiki/2/users/show)
//        let uid = dict["uid"]!
//        let parameters = ["access_token":token,"uid":uid]
//
//        HMNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
//            if error != nil {
//                SVProgressHUD.showError(withStatus: "你这个菜逼,没网还玩个蛋蛋")
//                return
//            }
//            
//            print(responseObject)  //将此数据挑选有效信息存放在模型中
//            //将用户信息存储在本地
//            //将授权之后的得到的字典和用户信息字典合并之后再存储
//            //授权之后得到的字典
//            var userInfoDict = responseObject as! [String : Any]
//            for(key,value) in dict{
//                userInfoDict[key] = value
//            }
//            
//            //字典转模型
//            let userAccount = WBUserAccount(dict: userInfoDict)
////            print(userAccount)
//            //存储模型对象到沙盒中Document目录下
//            self.saveUserAccount(userAccount: userAccount)
//        }
//    }
//    //存储模型对象,因此要传入参数模型
//    private func saveUserAccount(userAccount:WBUserAccount){
//
//        //存储模型,模型里要遵守NSCoding协议,实现协议方法
//        NSKeyedArchiver.archiveRootObject(userAccount, toFile: path)
//        
//        
//    }
//    //解档的时候有返回值,返回用户信息模型,?是因为当第一次的时候用户并没有登陆过并没有存储的信息
//    private func loadUserAccount()->(WBUserAccount?){
//        let account = NSKeyedUnarchiver.unarchiveObject(withFile: path)
//        if let userAccount = account as? WBUserAccount{
//            return userAccount
//        }
//        return nil
//    }
}
    
    

